﻿using System;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using CuteConsole.Mvvm;

namespace CuteConsole.Core
{
  public class Launcher
  {
    private static ConsoleModel _model;
    private static Thread _mainThread;
    private static readonly ManualResetEvent _mrt = new ManualResetEvent(false);

    public static void Main()
    {
      _mainThread = Thread.CurrentThread;

      var thread = new Thread(AuxiliaryThread);
      thread.SetApartmentState(ApartmentState.STA);
      thread.Start();
      _mrt.WaitOne();
 
      var userModule = new UserModuleWrapper(Assembly.GetCallingAssembly(), _model);
      userModule.Execute();
      
      thread.Join();
    }

    private static void AuxiliaryThread()
    {
      var application = new Application { MainWindow = new ConsoleView() };
      Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Normal,
         new Action(() =>
              {
                _model = new ConsoleModel();
                _mrt.Set();
                WindowModelHelper.Show(_model, Application.Current.MainWindow, false);
              }));
      application.Run();
      _mainThread.Abort();
    }
  }
}